<template>
  <div class="queuetime" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" @changeType='changeType' :query="query" @isFold="isShowFold" :isTimePeriod = "true" ref="timeChild" :isOther="true"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{$t('public.search2')}}</el-button>
            <div class="clear"></div></div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="skill">
                  <span class="ski">{{$t('public.queues')}}：</span>
                  <el-select size="mini"
                    v-model.trim="query.currentQueue"
                    :placeholder="$t('report.queueNaSea')"
                    multiple
                    filterable>
                    <el-option
                      v-for="item in queues"
                      :label="item.DisplayName"
                      :value="item._id"
                      :key="item._id">
                    </el-option>
                  </el-select>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.callQueueTimeSurvey')"></affix>
      <div class="situation">
        <el-row>
          <el-col v-for="(item, index) in situation" :span="8" :key="index">
            <span class="sum_name">{{item.name}}</span>
            <span class="sit_num">{{item.value}}</span>
          </el-col>
        </el-row>
      </div>
      <affix :label="$t('report.queueTimeRe')"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="options24out"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button class="primary_btn fr formal"  v-if="configFormula" @click="$refs.formulaEditorDialog.open()">{{$t('report.formalTitle')}}</el-button>
          <el-button class="primary_btn fr formal" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            v-on:click.stop="exportExcel"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->
          <el-button class="primary_btn fr formal"
            v-on:click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <el-select @change="search" v-if="$refs.timeChild && $refs.timeChild.form.timeType === 'day'" class="fr" size="mini" v-model="query.granularity" style="height:30px;width:120px;">
            <el-option :label="$t('report.oneHourTrend')" value="1h"/>
            <el-option :label="$t('report.halfHourTrend')" value="0.5h"/>
          </el-select>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                <p style="color: #ccc;
    margin: 5px 0;
    font-size: 12px;">{{ $t('report.callSkillHint') }}</p>
                {{$t('report.callConnectNum')}}<br>
                {{$t('report.connectioRate')}}<br>
                {{$t('report.callQueueTotalNum')}}<br>
                {{$t('report.twentySecondPick')}}<br>
                {{$t('report.turnOnaverQueuTime')}}<br>
                {{$t('report.callMaxQueueTime')}}<br>
                {{$t('report.callMinQueueTime')}}<br>
                {{$t('report.giveUpAverQueueTime')}}<br>
                {{$t('report.giveUpMaxQueueTime')}}<br>
                {{$t('report.giveUpMinQueueTime')}}<br>
                {{$t('report.callNotConnect')}}<br>
                {{$t('report.sixSecondGiveUp')}}<br>
                {{$t('report.averCallTime')}}<br>
                {{$t('report.serviceLevel')}}<br>
                15.{{$t('report.callTalkTime')}}<br>
                <!-- 17.{{$t('report.InOverflowCount')}}<br>
                18.{{$t('report.OutOverflowCount')}}<br> -->
                <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{index + 17}}.{{item.formulaInstr}}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="serveNumData" :sum="sum" :config="[...headOptions.Config,  ...formulasConfig]"> </report-table>
      </div>
      <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_queue_time" v-on:close="close" :headCustom="formulasConfig"></header-option>
      <!-- 自定义公式组件 -->
      <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config" @closeFormulaDialog="closeFormulaDialog" reportName="技能组时间趋势报表" :reportType="id"/>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../ui-modules/affix/Affix.vue'
  import unfold from '../../../ui-modules/unfold/index.vue'
  import dateTime from '../base/datetime.vue'
  import {exportReportPdf, checkTime, searchTime, colorConfigArr, headOptionsToXlsxHeaders, mixData} from '@/utils/reportUtils.js'
  import {deepClone, getCallTimeLength, getCache, optionTimeTypeCheck, isHasFunc} from '@/utils/m7Utils.js'
  import reportTable from '../base/reportTable.vue'
  import headerOption from '../base/headerOption.vue'
  import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
  import {sortBy} from 'lodash'

  export default {
    name: '',
    data () {
      return {
        configFormula: true, // 自定义公式的权限
        formulas: [], // 自定义公式的列表
        resData: [], // 查询的table的数据，用于自定义公式的计算
        isFold: false, // 是否展示搜索条件
        situation: [], // 概况渲染数据
        checkAll: true, // 省份全选绑定值
        loading: false, // 查询时展示加载的开关
        id: 'call_report_queue_time', // 查询id
        query: { // 查询条件时间信息等
          granularity: '0.5h', // 时间趋势
          currentQueue: []
        },
        queues: [], // 技能组信息
        serveNumData: [], // 表格table除合计数据
        sum: [], // 表格合计数据
        headOptionsShow: {}, // 配置表头用的数据
        headOptions: { // 表头数据
          Config: []
        },
        dateType:'',
        isShow: false, // 配置表头弹层开关
        dialogVisible: false, // 导出pdf开关
        options24out: {
          chart: {
            type: '',
            animation: false
          },
          colors: colorConfigArr,
          xAxis: {
            categories: []
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: {
              text: ''
            }
          },
          title: {
            text: this.$t('report.callReportQueueTime')
          },
          legend: {
            align: 'center',
            verticalAlign: 'top',
            x: 0,
            y: 20
          },
          tooltip: {
            shared: true
          },
          plotOptions: {
            column: {
              stacking: 'normal'
            },
            series: {animation: false}
          },
          credits: {enabled: false},
          series: []
        }
      }
    },
    watch: {
      // 监测自定义公式变化 更新数据
      formulas (cur, old) {
        if (this.isSearch) {
          return
        }
        if (!this.serveNumData || this.serveNumData.length === 0) {
          return
        }
        var queryData = this.getSearchQueryData()
        if (!queryData) {
          return
        }
        var {serveNumData, sum} = this.processDataAndSum(this.resData, this.headOptions, queryData)
        this.sum = sum
        this.serveNumData = deepClone(mixData(serveNumData, this.formulas))
      }
    },
    computed: {
      // 判断是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      // 自定义表头
      formulasConfig () {
        return this.formulas.map((d, i) => {
          return {
            displayname: d.displayname,
            name: d.name,
            order: d.order,
            show: d.show,
            timeType: 'none',
            digits: d.digits,
            type: d.type
          }
        })
      }
    },
    methods: {
      // 自定义公式弹窗关闭外抛事件
      closeFormulaDialog () {
        this.isSearch = false
        this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
          }
        })
      },
      changeType (val) {
        this.dateType = val
      },
      // 是否展开收起查询条件
      isShowFold (bool) {
        this.isFold = bool
      },
      // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 获取表头数据
      config () {
        this.$store.dispatch('getReportTableHeader', 'call_report_queue_time').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.callReportQueueTime') + searchTime(this.query), id: this.id})
      },
      // 抽出查询条件
      getSearchQueryData () {
        // 初始化查询条件
        let data = {
          reportType: 'call_report_queue_time',
          account: this.$store.state.session.user.account
        }
        let myQuery = deepClone(this.query)
        let isWeek = this.$refs.timeChild.form.timeType
        if (isWeek === 'week') {
          myQuery.timeType = 'other'
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        } else if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.currentQueue = myQuery.currentQueue.join(',')
        // 时间插件返回的是小写的timeType转大写的
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.reportType = 'call_report_queue_time'
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        data['query'] = myQuery
        return data
      },
      // 获取新的表格数据和合计数据，抽取共同
      processDataAndSum (tempData, headOptions, myQuery) {
        var sum = [{ReportTime: this.$t('report.total')}]
        // 计算合计
        for (let i in tempData) {
          let item = tempData[i]
          if (myQuery.TimeType === 'year') {
            item.ReportTime = item.MonthID
            delete item.MonthID
          } else if (myQuery.TimeType === 'month') {
            item.ReportTime = item.DayID
            delete item.DayID
          } else if ((myQuery.TimeType === 'other_half_hour') && myQuery.timePeriod) {
            //    查询方式为  自定义 或  日报  并且 定时间段统计  则更换 时间 渲染的字段
            item.ReportTime = item.DayID
            delete item.DayID
          } else {
            item.ReportTime = item._id
          }
          for (let j in item) {
            if (!isNaN(item[j]) && j !== 'ReportTime') {
              if ((j in sum[0]) === false) {
                sum[0][j] = 0
              }
              if (j === 'AcceptMaxQueueTimeLength') {
                if (item[j] > sum[0][j]) {
                  sum[0][j] = item[j]
                }
              } else if (j === 'AcceptMinQueueTimeLength') {
                if (item[j] !== 0) {
                  if (sum[0][j] === 0) {
                    sum[0][j] = item[j]
                  }
                  if (item[j] < sum[0][j]) {
                    sum[0][j] = item[j]
                  }
                }
              } else if (j === 'AbandonMaxQueueTimeLength') {
                if (item[j] > sum[0][j]) {
                  sum[0][j] = item[j]
                }
              } else if (j === 'AbandonMinQueueTimeLength') {
                if (item[j] !== 0) {
                  if (sum[0][j] === 0) {
                    sum[0][j] = item[j]
                  }
                  if (item[j] < sum[0][j]) {
                    sum[0][j] = item[j]
                  }
                }
              } else {
                sum[0][j] += item[j]
              }
            }
          }
          // 表格的数据时间化
          headOptions.Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getCallTimeLength(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = Math.round(item[option.name]) + 's'
            }
          })
        }
        var serveNumData = sortBy(tempData, 'ReportTime')

        // 合计字段时间化
        let Dividend = sum[0].AccessCount
        // 接通率小数点设置
        let zero = 0;
         headOptions.Config.forEach((item,index)=>{
          if(item.name == 'AcceptRate'){
            if(item.radixPoint){
              sum[0].AcceptRate = Dividend > 0 ? (Math.round((sum[0].AcceptCount / Dividend) * 100)).toFixed(item.radixPoint) : zero.toFixed(item.radixPoint)
            }else{
              sum[0].AcceptRate = Dividend > 0 ? Math.round((sum[0].AcceptCount / Dividend) * 100) : 0
            }
          }
        })
        // sum[0].AcceptRate = Dividend > 0 ? Math.round((sum[0].AcceptCount / Dividend) * 100) : 0
        // 放弃平均排队时长
        sum[0].AbandonAverageQueueTimeLength = sum[0].AccessCount - sum[0].AcceptCount > 0 ? sum[0].AbandonSumQueueTimeLength / (sum[0].AccessCount - sum[0].AcceptCount) : 0
        // 接通平均排队时长
        sum[0].AcceptAverageQueueTimeLength = sum[0].AcceptCount > 0 ? sum[0].AcceptSumQueueTimeLength / sum[0].AcceptCount : 0
        // 服务水平
        sum[0].ServiceLevel = sum[0].AccessCount === 0 ? 0 : Math.round((sum[0].AcceptIn20Count / sum[0].AccessCount) * 10) / 10
        // 平均通话时长
        sum[0].AcceptAverageCallInTimeLength = sum[0].AcceptCount > 0 ? Math.round(sum[0].AcceptSumCallInTimeLength / sum[0].AcceptCount) : 0
        // 不包含6秒放弃数接通率
        sum[0].AcceptRateNotIn6Leak = sum[0].AccessCount === 0 ? 0 : Math.round((sum[0].AcceptCount / (sum[0].AccessCount - sum[0].AbandonIn6SumQueueLeak)) * 100)
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            sum[0][option.name] = getCallTimeLength(sum[0][option.name])
          } else if (option.timeType && option.timeType === 'second') {
            sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
          } else if (option.name.indexOf('Rate') > -1 && option.displayname.indexOf('率') > -1) {
            sum[0][option.name] = `${sum[0][option.name]}%`
          }
        })
        if (sum[0].AcceptRate === '') {
          sum[0].ReportTime = ''
          sum[0].AbandonMinQueueTimeLength = ''
          sum[0].AbandonMaxQueueTimeLength = ''
          sum[0].AbandonAverageQueueTimeLength = ''
          sum[0].AcceptMinQueueTimeLength = ''
          sum[0].AcceptMaxQueueTimeLength = ''
          sum[0].AcceptAverageQueueTimeLength = ''
        }
        sum = mixData(sum, this.formulas)
        return {
          serveNumData,
          sum
        }
      },
      // 查询方法
      search () {
        var data = this.getSearchQueryData()

        if (!data) {
          return
        }
        var myQuery = data.query || deepClone(this.query)

        this.loading = true
        this.$store.dispatch('queryCallQueueTimeReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          if (!res.success) {
            this.loading = false
            return
          }
          this.$store.dispatch('queryFetchFormula', {type: this.id}).then((resp)=>{
            if (resp && resp.success && resp.data) {
              this.formulas = resp.data.Formulas || []
            }
            //  如果定时间段统计，图表标题加入定时段的时间
            let highchartsTitle = ''
            if (myQuery.timePeriod) {
              let timePeriodStartStr = myQuery.timePeriodStart || '00:00'
              let timePeriodEndStr = myQuery.timePeriodEnd || '23:59'
              highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
            }
            this.options24out.title.text = this.$t('report.callReportQueueTime') + highchartsTitle
            this.headOptions = optionTimeTypeCheck(res.tableHeader)
            let tempData = deepClone(res.data)
            this.options24out.xAxis.categories = []
            this.resData = res.data
            var {serveNumData, sum} = this.processDataAndSum(tempData, this.headOptions, myQuery)
            this.serveNumData = serveNumData
            this.sum = sum

            // 计算icharts图表的数据
            let series4high = {}
            this.options24out.xAxis.categories = []
            // 图表展示字段
            let showChartArr = ['AccessCount', 'AcceptCount', 'AcceptIn20Count', 'RepeatCallInBy24hCount', 'RepeatCallInBy48hCount']
            for (let i in this.serveNumData) {
              let item = this.serveNumData[i]
              this.options24out.xAxis.categories.push(item.ReportTime)
              for (let j in item) {
                if (series4high[j] === undefined) {
                  series4high[j] = []
                }
                if (showChartArr.indexOf(j) >= 0) {
                  series4high[j].push(item[j])
                } else {
                  delete series4high[j]
                }
              }
            }
            // 渲染icharts图表
            this.options24out.series = []
            this.situation = []
            for (let i in res.tableHeader.Config) {
              let item = res.tableHeader.Config[i]
              if (showChartArr.indexOf(item.name) >= 0) {
                // 渲染概况
                this.situation.push({
                  name: item.displayname,
                  value: this.sum[0][item.name] || 0
                })
                this.options24out.series.push({
                  name: item.displayname,
                  data: series4high[item.name]
                })
              }
            }
            this.loading = false
          })
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var data = this.getSearchQueryData()

        if (!data) {
          return
        }
        var myQuery = data.query || deepClone(this.query)

        this.loading = true
        this.$store.dispatch('queryCallQueueTimeReport', data).then((res) => {
          if (this.$store.state.report.customExportData) {
            res = JSON.parse(this.$store.state.report.customExportData)
          }
          this.loading = false
          var tempData = deepClone(mixData(res.data, this.formulas))
          var headOptions = optionTimeTypeCheck(res.tableHeader)
          var {sum} = this.processDataAndSum(tempData, this.headOptions, myQuery)
          if (tempData.length === 0) {
            sum = []
          }
          var tableData = tempData.concat(sum)
          var headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])
          var dh = XlsxUtil.getDownloadHelper(headers, tableData)
          var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
          dh.download(this.$t('report.callReportQueueTime') + timeStamp)
        })
      },
      // 导出表格数据执行的方法(后端)
      exportExcel () {
        let myQuery = deepClone(this.query)
        let isWeek = this.$refs.timeChild.form.timeType
        if (isWeek === 'week') {
          myQuery.timeType = 'other'
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        } else if (myQuery.timeType === 'other_half_hour') {
          // 校验类型与时间
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false)
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        // 时间插件返回的是小写的timeType转大写的
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.currentQueue = myQuery.currentQueue.join(',')
        myQuery.reportType = 'call_report_queue_time'
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'exportReportQueueTime'
        myQuery.user = this.$store.state.session.user._id
        if (myQuery.TimeType === 'year') {
          delete myQuery.monthReport
          delete myQuery.dayReport
        }
        let data = {
          Method: 'exportReportQueueTime',
          Query: myQuery
        }
        this.$store.dispatch('exportCallQueueTimeReport', data).then(() => {
        })
      }
    },
    components: {
      affix,
      unfold,
      dateTime,
      reportTable,
      headerOption,
      FormulaEditorDialog
    },
    beforeMount () {
      if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
        this.configFormula = false // 没有自定义公式的配置权限
      }
      this.$store.dispatch('getCache', {type: 'queues'}).then(() => {
        this.queues = getCache('queues')
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .tip
    cursor pointer
    display inline-block
    border 1px solid #459ae9
    text-align center
    line-height 16px
    border-radius 50%
    margin 0 0 0 6px
    width 16px
  .formal
    margin-left 10px
  .queuetime
    .skill
      .el-select
        width 400px
</style>
